package net.adetech.dcweb.core.${DBEntity.packageName}.service.impl;

import net.adetech.utils.condition.ConditionEntity;
import net.adetech.utils.condition.ConditionTools;
import net.adetech.utils.condition.SQLEntity;
import net.adetech.utils.spring.PageBean;
import net.adetech.dcweb.core.${DBEntity.packageName}.service.I${DBEntity.pascalName}Service;
import net.adetech.dcweb.core.${DBEntity.packageName}.entity.${DBEntity.pascalName};
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import java.sql.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.HashSet;
import org.springframework.jdbc.core.JdbcTemplate;

/**
* Created by sunfeihu on 2016/10/20.
*/
@Service
public class ${DBEntity.pascalName}ServiceImpl implements I${DBEntity.pascalName}Service {

private final Logger logger = LoggerFactory.getLogger(${DBEntity.pascalName}ServiceImpl.class);

@Autowired
private JdbcTemplate jdbcTemplate;

@Override
public ${DBEntity.pascalName} save(${DBEntity.pascalName} entity) {
final String sql = " insert into ${DBEntity.tableName} (${DBEntity.insertField}) values(${DBEntity.insertQField})";
KeyHolder keyHolder = new GeneratedKeyHolder();
final ${DBEntity.pascalName} finalEntity = entity;
jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
<#list DBEntity.fieldsNoId as field>
    <#if field.DATA_TYPE=='datetime'>
    if (null != finalEntity.get${field.COLUMN_NAME}()) {
    ps.setObject(${field_index+1}, new java.sql.Timestamp(finalEntity.get${field.COLUMN_NAME}().getTime()));
    }else{
    ps.setObject(${field_index+1}, null);
    }
    <#else>
    ps.setObject(${field_index+1}, finalEntity.get${field.COLUMN_NAME}());
    </#if>
</#list>
return ps;
}
}, keyHolder);
Long id = keyHolder.getKey().longValue();
return this.find(id);
}

@Override
public int delete(Long id) {
final String sql = " update ${DBEntity.tableName} set is_delete = 1 where id = ? ";
return jdbcTemplate.update(sql, new Object[]{
id
});
}

@Override
public int update(${DBEntity.pascalName} entity) {
final String sql = " update ${DBEntity.tableName} set ${DBEntity.updateField} where id = ?";
return jdbcTemplate.update(sql, new Object[]{
<#list DBEntity.fieldsNoId as field>
    <#if field.COLUMN_NAME!='Uuid'&&field.COLUMN_NAME!='AddDate'&&field.COLUMN_NAME!="AddIp"&&field.COLUMN_NAME!="AddUser"&&field.COLUMN_NAME!="UpdateIp"&&field.COLUMN_NAME!="UpdateDate"&&field.COLUMN_NAME!="UpdateUser"&&field.COLUMN_NAME!="IsDelete">
    entity.get${field.COLUMN_NAME}(),
    </#if>
</#list>
entity.getId()
});
}

@Override
public ${DBEntity.pascalName} find(Long id) {
final String sql = " select * from ${DBEntity.tableName} where id = ? and is_delete = 0 ";
try {
return jdbcTemplate.queryForObject(sql,new Object [] {id}, new ${DBEntity.pascalName}RowerMapper());
} catch (DataAccessException e) {
return null;
}
}

@Override
public void save(List<${DBEntity.pascalName}> list) {
if (null != list && list.size() > 0) {
final String sql = " insert into ${DBEntity.tableName} (${DBEntity.insertField}) values(${DBEntity.insertQField})";
List
<Object[]> params = new ArrayList
<Object[]>();
Object[] objArr = null;
${DBEntity.pascalName} entity = null;
for (int i = 0; i < list.size(); i++) {
entity = list.get(i);
objArr = new Object[${DBEntity.fieldsNoId?size}];
<#list DBEntity.fieldsNoId as field>
objArr[${field_index}] = entity.get${field.COLUMN_NAME}();
</#list>
params.add(objArr);
}
jdbcTemplate.batchUpdate(sql, params);
}
}

@Override
public void delete(List
<Long> ids) {
    if (null != ids && ids.size() > 0) {
    final String sql = " update ${DBEntity.tableName} set is_delete = 1 where id = ? ";
    List
    <Object
    []> params = new ArrayList
    <Object
    []>();
    Object[] objArr = null;
    for (int i = 0; i < ids.size(); i++) {
    objArr = new Object[1];
    objArr[0] = ids.get(i);
    params.add(objArr);
    }
    jdbcTemplate.batchUpdate(sql, params);
    }
    }

    @Override
    public void update(List<${DBEntity.pascalName}> list) {
    if (null != list && list.size() > 0) {
    final String sql = " update ${DBEntity.tableName} set ${DBEntity.updateField} where id = ?";
    List
    <Object
    []> params = new ArrayList
    <Object
    []>();
    Object[] objArr = null;
${DBEntity.pascalName} entity = null;
    for (int i = 0; i < list.size(); i++) {
    entity = list.get(i);
    objArr = new Object[${DBEntity.fieldsNoDefault?size}];
<#list DBEntity.fieldsNoDefault as field>
    objArr[${field_index}] = entity.get${field.COLUMN_NAME}();
</#list>
    objArr[${DBEntity.fieldsNoDefault?size}] = entity.getId();
    params.add(objArr);
    }
    jdbcTemplate.batchUpdate(sql, params);
    }
    }

    @Override
    public PageBean<${DBEntity.pascalName}> page(int nowPage, int pageSize ,ConditionEntity conditionEntity) {
    SQLEntity sqlEntity = ConditionTools.conditionEntities2SQL(conditionEntity);
    final String sql = " select * from ${DBEntity.tableName} where 1 = 1 and is_delete = 0 " + sqlEntity.getSql() + " order by " + sqlEntity.getOrder();
    return new PageBean<${DBEntity.pascalName}>(sql, sqlEntity.getParams(), nowPage, pageSize,
    new ${DBEntity.pascalName}RowerMapper(), jdbcTemplate);
    }
    }


    class ${DBEntity.pascalName}RowerMapper implements RowMapper<${DBEntity.pascalName}>{
    @Override
    public ${DBEntity.pascalName} mapRow(ResultSet rs, int rowNum) throws SQLException {
    ResultSetMetaData rsmd = rs.getMetaData();
    int columnCount = rsmd.getColumnCount();
    Set
    <String> fieldSet = new HashSet
        <String>();
            for (int i = 1; i <= columnCount; i++) {
            fieldSet.add(rsmd.getColumnLabel(i));
            }
        ${DBEntity.pascalName} entity = new ${DBEntity.pascalName}();
        <#list DBEntity.pascalFields?keys as field>
            if(fieldSet.contains("${DBEntity.hungarianNotationFields[field].COLUMN_NAME}") && null !=
            rs.getObject("${DBEntity.hungarianNotationFields[field].COLUMN_NAME}")){
            <#if DBEntity.pascalFields[field].DATA_TYPE=='datetime'>
                entity.set${DBEntity.pascalFields[field].COLUMN_NAME}(new
                java.util.Date(rs.getTimestamp("${DBEntity.hungarianNotationFields[field].COLUMN_NAME}").getTime()));
            <#else>
                entity.set${DBEntity.pascalFields[field].COLUMN_NAME}(rs.get${DBEntity.pascalFields[field].MAPPER_TYPE}
                ("${DBEntity.hungarianNotationFields[field].COLUMN_NAME}"));
            </#if>
            }
        </#list>
            return entity;
            }
            }